package vns.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import vns.client.service.RoleService;
import vns.server.domain.RuleAction;
import vns.server.domain.ObjectType;
import vns.server.domain.Role;
import vns.shared.RuleActionDTO;
import vns.shared.ObjectPropertyTypeDTO;
import vns.shared.ObjectTypeDTO;
import vns.shared.RoleDTO;

import com.google.appengine.api.datastore.Key;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RoleServiceImpl extends RemoteServiceServlet implements
		RoleService {

	@Override
	public RoleDTO Create(RoleDTO roleDTO) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Role action = null;
		try {
			action = new Role(roleDTO);
			pm.makePersistent(action);
		} finally {
			pm.close();
		}
		return action.toDTO();
	}

	@Override
	public boolean Remove(Key id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Role action = pm.getObjectById(Role.class, id);
			if (action != null) {
				pm.deletePersistent(pm.getObjectById(Role.class, id));
			}
		} finally {
			pm.close();
		}
		return true;
	}

	@Override
	public RoleDTO Loadbyid(Key id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		RoleDTO actionDTO = null;
		try {
			Role action = pm.getObjectById(Role.class, id);
			actionDTO = action.toDTO();
		} finally {
			pm.close();
		}
		return actionDTO;
	}

	@Override
	public RoleDTO Update(RoleDTO roleDTO) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Role action = null;
		try {
			action = pm.getObjectById(Role.class, roleDTO.getId());
			action.updatefromDTO(roleDTO);
		} finally {
			pm.close();
		}

		return action.toDTO();
	}

	@Override
	public ArrayList<RoleDTO> Loadall() {
		ArrayList<RoleDTO> listactionDTO = new ArrayList<RoleDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Role.class);
		try {
			List<Role> res = (List<Role>) q.execute();
			for (Role actiontype : res) {
				listactionDTO.add(actiontype.toDTO());
			}
		} finally {
			pm.close();
		}
		return listactionDTO;
	}

	@Override
	public void Updateall(List<RoleDTO> listNew) {
		ArrayList<RoleDTO> listOld = this.Loadall();
		for (RoleDTO element : listNew) {
			if (!containInList(listOld, element)) {
				element = this.Create(element);
			} else {
				this.Update(element);
			}
		}
		for (RoleDTO element : listOld) {
			if (!containInList(listNew, element)) {
				this.Remove(element.getId());
			}
		}

	}

	private boolean containInList(List<RoleDTO> list, RoleDTO element) {
		if (element.getId() == null)
			return false;
		for (RoleDTO optDTO : list) {
			if (optDTO.getId().equals(element.getId()))
				return true;
		}
		return false;
	}
}
